import {defineStore} from 'pinia';
import axios from "axios";
import {useProductStore, useUserStore} from "@/stores/index.js";
import {message} from "ant-design-vue";

export const useCartStore = defineStore('cart', {
    state: () => ({
        cartItems: [],
    }),
    actions: {
        async fetchCartItems() {
            const userId = useUserStore().userInfo ? useUserStore().userInfo.userId : null;
            if (!userId) {
                message.error("请先登录");
                return;
            }
            try {
                const response = await axios.post('/api/cart/getUserCart', {userId: userId});
                if (response.data.code === 200) {
                    console.log(response.data.data);
                    this.cartItems = response.data.data;
                }
            } catch (error) {
                console.error('获取购物车失败', error);
            }
        },
        async toggleProductInCart(product) {
            const existingItem = this.cartItems.find(item => item.productId === product.productId);
            if (!useUserStore().userInfo.userId) {
                message.error("请先登录");
                return;
            }
            if (existingItem) {
                // 如果商品已在购物车中，则移除
                return this.removeProductFromCart(product.productId);
            } else {
                // 如果商品不在购物车中，则添加
                return this.addProductToCart(product);
            }
        },
        async addProductToCart(product) {
            try {
                const userId = useUserStore().userInfo ? useUserStore().userInfo.userId : null;
                if (!userId) {
                    message.error("请先登录");
                    return;
                }
                const response = await axios.post('/api/cart/add', {
                    productId: product.productId,
                    userId: userId,
                    quantity: 1
                });
                if (response.data.code === 200) {
                    this.cartItems.push({...product, quantity: 1});
                }
                return true;
            } catch (error) {
                console.error('加入购物车失败', error);
                return false;
            }
        },
        async removeProductFromCart(productId) {
            try {
                const userId = useUserStore().userInfo ? useUserStore().userInfo.userId : null;
                if (!userId) {
                    return false;
                }
                const response = await axios.post('/api/cart/remove', {
                    productId: productId,
                    userId: userId
                });
                if (response.data.code === 200) {
                    this.cartItems = this.cartItems.filter(item => item.productId !== productId);
                }
                return true;
            } catch (error) {
                console.error('从购物车移除失败', error);
                return false;
            }
        },
        // 暂时没用到
        async updateProductQuantity(productId, quantity) {
            try {
                const response = await axios.post('/api/cart/update', {
                    productId: productId,
                    quantity: quantity
                });
                if (response.data.code === 200) {
                    const item = this.cartItems.find(item => item.id === productId);
                    if (item) {
                        item.quantity = quantity;
                    }
                }
            } catch (error) {
                console.error('更新购物车数量失败', error);
            }
        }
    },
    getters: {
        cartItemCount() {
            return this.cartItems.reduce((total, item) => total + item.quantity, 0);
        },
        cartTotal() {
            const productStore = useProductStore();
            return this.cartItems.reduce((total, item) => {
                const product = productStore.getProductById(item.productId);
                return total + (product ? product.price * item.quantity : 0);
            }, 0);
        },
        isProductInCart: (state) => (productId) => {
            return state.cartItems.some(item => item.productId === productId);
        },
        cartItemsWithDetails() {
            const productStore = useProductStore();
            return this.cartItems.map(item => {
                const product = productStore.getProductById(item.productId);
                return { ...item, ...product };
            });
        }
    }
});
